package org.vsg.security.model.presentation.spring;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Collection;
import java.util.Set;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.vsg.common.pagination.Pagination;
import org.vsg.common.pagination.apps.HttpApplicationContext;
import org.vsg.common.pagination.apps.HttpPaginationApplicationContextFactory;
import org.vsg.common.pagination.apps.PaginationApplicationContext;
import org.vsg.common.pagination.apps.RecordLimitCarrierApplicationContext;
import org.vsg.common.pagination.carrier.HttpSingleSortRecordLimitCarrier;
import org.vsg.common.pagination.carrier.RecordLimitCarrier;
import org.vsg.common.web.json.ListResult;
import org.vsg.common.web.json.LoadRecordResult;
import org.vsg.common.web.json.SubmitResult;
import org.vsg.common.web.json.processor.JsTimestampJsonValueProcessor;
import org.vsg.security.model.domain.SysRole;
import org.vsg.security.model.service.SysRoleService;
import org.vsg.security.model.vo.json.SysRoleListVO;
import org.vsg.security.model.vo.json.SysRoleSimpleFormVO;

@Controller
public class RoleController {

	private final static Logger logger = LoggerFactory.getLogger(RoleController.class);	
	
	
	@Autowired
	private SysRoleService sysRoleService;
	
	@RequestMapping("/pageRole.do")
	public String pageRole(HttpServletRequest req , HttpServletResponse res) throws Exception {
		// TODO Auto-generated method stub

		// generate pagination application and set the request
		PaginationApplicationContext pageAppsContext = HttpPaginationApplicationContextFactory.getPaginationContext(req);
		// set parameter passed in pagination url
		RecordLimitCarrierApplicationContext recordLimitAppsContenxt = (RecordLimitCarrierApplicationContext)pageAppsContext;
		
		HttpApplicationContext httpContext = (HttpApplicationContext)pageAppsContext;
		
		httpContext.addParameterName("name");
		httpContext.addParameterName("code");		
		httpContext.addParameterName("flagInactive");		
		
		// set the data to attribute
		RecordLimitCarrier limitCarrier = recordLimitAppsContenxt.generateRecordLimitCarrier( HttpSingleSortRecordLimitCarrier.class );
		
		Pagination page = sysRoleService.pageSysRole(limitCarrier);
		
		
		Collection<SysRole> sysRoleList = page.getPaginationList();
		
		Collection<SysRoleListVO> tmpRoleVoList = new Vector<SysRoleListVO>();
		for (SysRole role : sysRoleList) {
			tmpRoleVoList.add(new SysRoleListVO(role));
		}
		
		// --- parse the json ---
		ListResult lr = new ListResult();
		lr.setResults( page.getTotalRecord() );
		lr.setRows( tmpRoleVoList );
		
		JsonConfig jcfg = new JsonConfig();
		jcfg.registerJsonValueProcessor(java.sql.Timestamp.class, new JsTimestampJsonValueProcessor());
		JSONObject jsonObject = JSONObject.fromObject(lr ,jcfg ); 
		
		// --- set attribute ---
		req.setAttribute("json", jsonObject);
		
		return "json";
	}
	
	@RequestMapping("/pageHierarchyRole.do")
	public String pageHierarchyRole(HttpServletRequest req , HttpServletResponse res) throws Exception {

		// generate pagination application and set the request
		PaginationApplicationContext pageAppsContext = HttpPaginationApplicationContextFactory.getPaginationContext(req);
		// set parameter passed in pagination url
		RecordLimitCarrierApplicationContext recordLimitAppsContenxt = (RecordLimitCarrierApplicationContext)pageAppsContext;
		
		HttpApplicationContext httpContext = (HttpApplicationContext)pageAppsContext;
		
		httpContext.addParameterName("name");
		
		// set the data to attribute
		RecordLimitCarrier limitCarrier = recordLimitAppsContenxt.generateRecordLimitCarrier( HttpSingleSortRecordLimitCarrier.class );
		
		Pagination page = sysRoleService.pageSysRoleHierarchy(limitCarrier);
		
		Collection<SysRole> sysRoleList = page.getPaginationList();
		
		Collection<SysRoleListVO> tmpRoleVoList = new Vector<SysRoleListVO>();
		for (SysRole role : sysRoleList) {
			tmpRoleVoList.add(new SysRoleListVO(role));
		}
		
		// --- parse the json ---
		ListResult lr = new ListResult();
		lr.setResults( page.getTotalRecord() );
		lr.setRows( tmpRoleVoList );
		
		JsonConfig jcfg = new JsonConfig();
		jcfg.registerJsonValueProcessor(java.sql.Timestamp.class, new JsTimestampJsonValueProcessor());
		JSONObject jsonObject = JSONObject.fromObject(lr ,jcfg ); 
		
		// --- set attribute ---
		req.setAttribute("json", jsonObject);		
		
		return "json";
	}
	
	
	@RequestMapping("/showDependenceRoles.do")
	public String showDependenceRoles(HttpServletRequest req ,int roleId) throws Exception {
		
		SysRole sysRole = sysRoleService.loadSysRole(roleId);

		Set<SysRole> sysRoleList = sysRole.getDependenceRoles();
		
		Collection<SysRoleListVO> tmpRoleVoList = new Vector<SysRoleListVO>();
		for (SysRole role : sysRoleList) {
			tmpRoleVoList.add(new SysRoleListVO(role));
		}

		// --- parse the json ---
		ListResult lr = new ListResult();
		lr.setResults( tmpRoleVoList.size() );
		lr.setRows( tmpRoleVoList );
		
		JsonConfig jcfg = new JsonConfig();
		jcfg.registerJsonValueProcessor(java.sql.Timestamp.class, new JsTimestampJsonValueProcessor());
		JSONObject jsonObject = JSONObject.fromObject(lr ,jcfg ); 
		
		// --- set attribute ---
		req.setAttribute("json", jsonObject);		
		
		return "json";
	}
	
	@RequestMapping("/showConflictRoles.do")
	public String showConflictRoles(HttpServletRequest req ,int roleId) throws Exception {
		SysRole sysRole = sysRoleService.loadSysRole(roleId);

		Set<SysRole> sysRoleList = sysRole.getConflictRoles();
		
		Collection<SysRoleListVO> tmpRoleVoList = new Vector<SysRoleListVO>();
		for (SysRole role : sysRoleList) {
			tmpRoleVoList.add(new SysRoleListVO(role));
		}

		// --- parse the json ---
		ListResult lr = new ListResult();
		lr.setResults( tmpRoleVoList.size() );
		lr.setRows( tmpRoleVoList );
		
		JsonConfig jcfg = new JsonConfig();
		jcfg.registerJsonValueProcessor(java.sql.Timestamp.class, new JsTimestampJsonValueProcessor());
		JSONObject jsonObject = JSONObject.fromObject(lr ,jcfg ); 
		
		// --- set attribute ---
		req.setAttribute("json", jsonObject);		
		
		return "json";
	}

	
	@RequestMapping("/pageAvailableHierarchyRoleForOne.do")	
	public String pageAvailableHierarchyRoleForOne(HttpServletRequest req , HttpServletResponse res) throws Exception {

		// generate pagination application and set the request
		PaginationApplicationContext pageAppsContext = HttpPaginationApplicationContextFactory.getPaginationContext(req);
		// set parameter passed in pagination url
		RecordLimitCarrierApplicationContext recordLimitAppsContenxt = (RecordLimitCarrierApplicationContext)pageAppsContext;
		
		HttpApplicationContext httpContext = (HttpApplicationContext)pageAppsContext;
		
		httpContext.addParameterName("roleId");
		
		// set the data to attribute
		RecordLimitCarrier limitCarrier = recordLimitAppsContenxt.generateRecordLimitCarrier( HttpSingleSortRecordLimitCarrier.class );
		
		Pagination page = sysRoleService.pageAvailableHierarchyRolesForOne(limitCarrier);
		
		Collection<SysRole> sysRoleList = page.getPaginationList();
		
		Collection<SysRoleListVO> tmpRoleVoList = new Vector<SysRoleListVO>();
		for (SysRole role : sysRoleList) {
			tmpRoleVoList.add(new SysRoleListVO(role));
		}
		
		// --- parse the json ---
		ListResult lr = new ListResult();
		lr.setResults( page.getTotalRecord() );
		lr.setRows( tmpRoleVoList );
		
		JsonConfig jcfg = new JsonConfig();
		jcfg.registerJsonValueProcessor(java.sql.Timestamp.class, new JsTimestampJsonValueProcessor());
		JSONObject jsonObject = JSONObject.fromObject(lr ,jcfg ); 
		
		// --- set attribute ---
		req.setAttribute("json", jsonObject);			
		
		return "json";
	}

	@RequestMapping("/pageAvailableHierarchyRole.do")	
	public String pageAvailableHierarchyRole(HttpServletRequest req , HttpServletResponse res) throws Exception {

		
		// generate pagination application and set the request
		PaginationApplicationContext pageAppsContext = HttpPaginationApplicationContextFactory.getPaginationContext(req);
		// set parameter passed in pagination url
		RecordLimitCarrierApplicationContext recordLimitAppsContenxt = (RecordLimitCarrierApplicationContext)pageAppsContext;
		
		HttpApplicationContext httpContext = (HttpApplicationContext)pageAppsContext;
		
		httpContext.addParameterName("roleId");
		
		// set the data to attribute
		RecordLimitCarrier limitCarrier = recordLimitAppsContenxt.generateRecordLimitCarrier( HttpSingleSortRecordLimitCarrier.class );
		
		Pagination page = sysRoleService.pageAvailableHierarchyRoles(limitCarrier);
		
		Collection<SysRole> sysRoleList = page.getPaginationList();
		
		Collection<SysRoleListVO> tmpRoleVoList = new Vector<SysRoleListVO>();
		for (SysRole role : sysRoleList) {
			tmpRoleVoList.add(new SysRoleListVO(role));
		}
		
		// --- parse the json ---
		ListResult lr = new ListResult();
		lr.setResults( page.getTotalRecord() );
		lr.setRows( tmpRoleVoList );
		
		JsonConfig jcfg = new JsonConfig();
		jcfg.registerJsonValueProcessor(java.sql.Timestamp.class, new JsTimestampJsonValueProcessor());
		JSONObject jsonObject = JSONObject.fromObject(lr ,jcfg ); 
		
		// --- set attribute ---
		req.setAttribute("json", jsonObject);			
		
		return "json";
	}
	
	
	
	@RequestMapping("/pageUndefinedHierarchyRole.do")
	public String pageUndefinedHierarchyRole(HttpServletRequest req , HttpServletResponse res) throws Exception {
		
		// generate pagination application and set the request
		PaginationApplicationContext pageAppsContext = HttpPaginationApplicationContextFactory.getPaginationContext(req);
		// set parameter passed in pagination url
		RecordLimitCarrierApplicationContext recordLimitAppsContenxt = (RecordLimitCarrierApplicationContext)pageAppsContext;
		
		HttpApplicationContext httpContext = (HttpApplicationContext)pageAppsContext;
		
		// set the data to attribute
		RecordLimitCarrier limitCarrier = recordLimitAppsContenxt.generateRecordLimitCarrier( HttpSingleSortRecordLimitCarrier.class );
		
		Pagination page = sysRoleService.pageUndefinedHierarchyRoles(limitCarrier);
		
		Collection<SysRole> sysRoleList = page.getPaginationList();
		
		Collection<SysRoleListVO> tmpRoleVoList = new Vector<SysRoleListVO>();
		for (SysRole role : sysRoleList) {
			tmpRoleVoList.add(new SysRoleListVO(role));
		}
		
		// --- parse the json ---
		ListResult lr = new ListResult();
		lr.setResults( page.getTotalRecord() );
		lr.setRows( tmpRoleVoList );
		
		JsonConfig jcfg = new JsonConfig();
		jcfg.registerJsonValueProcessor(java.sql.Timestamp.class, new JsTimestampJsonValueProcessor());
		JSONObject jsonObject = JSONObject.fromObject(lr ,jcfg ); 
		
		// --- set attribute ---
		req.setAttribute("json", jsonObject);	
		
		return "json";
	}
	
	@RequestMapping("/pageAvailableConflictRole.do")	
	public String pageAvailableConflictRole( HttpServletRequest req , HttpServletResponse res ) throws Exception {
		
		// generate pagination application and set the request
		PaginationApplicationContext pageAppsContext = HttpPaginationApplicationContextFactory.getPaginationContext(req);
		// set parameter passed in pagination url
		RecordLimitCarrierApplicationContext recordLimitAppsContenxt = (RecordLimitCarrierApplicationContext)pageAppsContext;
		
		HttpApplicationContext httpContext = (HttpApplicationContext)pageAppsContext;
		
		httpContext.addParameterName("roleId");
		
		// set the data to attribute
		RecordLimitCarrier limitCarrier = recordLimitAppsContenxt.generateRecordLimitCarrier( HttpSingleSortRecordLimitCarrier.class );
		
		Pagination page = sysRoleService.pageAvailableConflictRole(limitCarrier);
		
		Collection<SysRole> sysRoleList = page.getPaginationList();
		
		Collection<SysRoleListVO> tmpRoleVoList = new Vector<SysRoleListVO>();
		for (SysRole role : sysRoleList) {
			tmpRoleVoList.add(new SysRoleListVO(role));
		}
		
		// --- parse the json ---
		ListResult lr = new ListResult();
		lr.setResults( page.getTotalRecord() );
		lr.setRows( tmpRoleVoList );
		
		JsonConfig jcfg = new JsonConfig();
		jcfg.registerJsonValueProcessor(java.sql.Timestamp.class, new JsTimestampJsonValueProcessor());
		JSONObject jsonObject = JSONObject.fromObject(lr ,jcfg ); 
		
		// --- set attribute ---
		req.setAttribute("json", jsonObject);			
		return "json";		
	}
	
	/**
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/addRole.do")
	public String addRole(HttpServletRequest req , HttpServletResponse res , SysRole role) throws Exception {
		
		Calendar cale = Calendar.getInstance();

		role.setCreatedDate( new Timestamp(cale.getTimeInMillis()) );
		
		// insert role
		sysRoleService.addSysRole( role );
		
		// --- json result object ---
		SubmitResult submitResult = new SubmitResult();
		submitResult.setSuccess(true);
		submitResult.setMsg( "新增成功!" );
		
		JSONObject jsonObject = JSONObject.fromObject(submitResult ); 
		
		req.setAttribute("json", jsonObject);
		
		return "result";
	}
	
	@RequestMapping("/updateRole.do")
	public String updateRole(HttpServletRequest req , HttpServletResponse res , SysRole role) throws Exception {

		sysRoleService.updateSimpleSysRole(role);
		
		// --- json result object ---
		SubmitResult submitResult = new SubmitResult();
		submitResult.setSuccess(true);
		submitResult.setMsg( "修改成功!" );		
		JSONObject jsonObject = JSONObject.fromObject(submitResult ); 
		
		req.setAttribute("json", jsonObject);			
		
		return "result";
	}
	
	@RequestMapping("/loadRole.do")
	public String loadRole(HttpServletRequest req , HttpServletResponse res , int roleId) throws Exception {
		
		SysRole sysRole = sysRoleService.loadSysRole(roleId);
		
		// --- json result object ---
		LoadRecordResult recordResult = new LoadRecordResult();
		recordResult.setSuccess(true);
		recordResult.setData( new SysRoleSimpleFormVO(sysRole) );

		JsonConfig jcfg = new JsonConfig();
		jcfg.registerJsonValueProcessor(java.sql.Timestamp.class, new JsTimestampJsonValueProcessor());

		JSONObject jsonObject = JSONObject.fromObject( recordResult  , jcfg); 
		
		logger.debug( jsonObject.toString() );
	
		req.setAttribute("json", jsonObject);
				
		return "result";
	}

	@RequestMapping("/removeRoles.do")
	public String removeRoles(HttpServletRequest req , HttpServletResponse res , int[] roleId) throws Exception {
		
		sysRoleService.removeRoles(roleId);
		
		// ------------ add response message
		
		// --- json result object ---
		SubmitResult submitResult = new SubmitResult();
		submitResult.setSuccess(true);
		submitResult.setMsg( "移除角色数据成功" );

		JSONObject jsonObject = JSONObject.fromObject(submitResult ); 
		
		req.setAttribute("json", jsonObject);
		
		// --- use log show
		logger.info(jsonObject.toString());	
		
		return "result";
	}

	@RequestMapping("/updateRoleHierarchy.do")
	public String updateRoleHierarchy(HttpServletRequest req , HttpServletResponse res , SysRole role) throws Exception {

		String bePartOfRole = req.getParameter("bePartOfRole");
		String[] partOfRoles = bePartOfRole.split(",");
		
		sysRoleService.updateRoleHierarchy( role , partOfRoles);
		

		
		// --- json result object ---
		SubmitResult submitResult = new SubmitResult();
		submitResult.setSuccess(true);
		submitResult.setMsg( "更新角色依赖成功!" );	
		JSONObject jsonObject = JSONObject.fromObject(submitResult ); 
		
		req.setAttribute("json", jsonObject);		
		
		return "result";
	}
	
	@RequestMapping("/addRoleConflict.do")
	public String addRoleConflict(HttpServletRequest req , HttpServletResponse res, int roleId , String[] conflictRolesId) throws Exception {
		SysRole mainRole = new SysRole();
		mainRole.setId( roleId );
		
		sysRoleService.addRoleConflict(mainRole, conflictRolesId);
		
		// --- json result object ---
		SubmitResult submitResult = new SubmitResult();
		submitResult.setSuccess(true);
		submitResult.setMsg( "添加约束成功!" );		
		JSONObject jsonObject = JSONObject.fromObject(submitResult ); 
		
		req.setAttribute("json", jsonObject);
		
		return "result";
	}
	
	@RequestMapping("/removeRoleConflict.do")
	public String removeRoleConflict(HttpServletRequest req , HttpServletResponse res, int roleId , String[] conflictRolesId) throws Exception {
		SysRole mainRole = new SysRole();
		mainRole.setId( roleId );
		
		sysRoleService.removeRoleConflict(mainRole, conflictRolesId);
		
		
		// --- json result object ---
		SubmitResult submitResult = new SubmitResult();
		submitResult.setSuccess(true);
		submitResult.setMsg("移除约束成功!" );		
		JSONObject jsonObject = JSONObject.fromObject(submitResult ); 
		
		req.setAttribute("json", jsonObject);
		
		return "result";
	}	
	
}
